package com.zhanghaojia.wyn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 张好佳
 * @date 2022年01月01日 10:50 PM
 * 原生方法封装websocket
 */
@Component
@ServerEndpoint(value = "/websocket/{username}")
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    /**
     * 在线客户端数量
     *
     */
    public static final Map<String,Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username")String userName) {
        System.out.println(userName+"连接成功");
        sessionMap.put(userName,session);

        //发送在线用户列表
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        result.put("users",jsonArray);
        for (String key : sessionMap.keySet()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName",key);
            jsonArray.add(jsonObject);
        }

        sendAllMessage(result.toJSONString());

    }

    //将在线信息发给所有客户端
    private void sendAllMessage(String message) {
        try {
            for (Session value : sessionMap.values()) {
                value.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //将在线信息发给所有客户端
    private void sendToUserMessage(String userName,String message) {
        try {
            if (sessionMap.containsKey(userName)){
                Session session = sessionMap.get(userName);
                session.getBasicRemote().sendText(message);
            }else {
                log.info("{}用户不在线",userName);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session,@PathParam("username") String userName) {
        System.out.println(userName + "连接关闭");
        sessionMap.remove(userName);
        sendAllMessage(userName+"已下线");

    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public String onMsg(String text,@PathParam("username")String userName) throws IOException {
        System.out.println("来自客户端的消息:" + text);
        JSONObject jsonObject = JSONObject.parseObject(text);
        String toUserName = jsonObject.getString("to");
        String message = jsonObject.getString("message");
        JSONObject messageSend = new JSONObject();
        messageSend.put("from",userName);
        messageSend.put("message",message);
        sendToUserMessage(toUserName,messageSend.toJSONString());
        return "servet 发送："+toUserName + text;
    }
    
}

